var selectedMenuid = -1;
var menuData = {};

/**
 * 菜单树自定义菜单事件
 * @param node
 * @returns {{createItem: {label: string, action: createItem.action}, renameItem: {label: string, action: renameItem.action}, deleteItem: {label: string, action: deleteItem.action}}}
 */
function customMenu(node) {
    var parentMenu = {
        createItem: {
            label: "添加子菜单",
            action: function (node) {
                var selected = $("#tree").jstree("get_selected");
                var obj = $("#tree").jstree("get_node", selected[0]);
                addMenu(obj);
            }
        }
    };

    var sonMenu = {
        createItem: {
            label: "添加子菜单",
            action: function (node) {
                var selected = $("#tree").jstree("get_selected");
                var obj = $("#tree").jstree("get_node", selected[0]);
                addMenu(obj);
            }
        },

        renameItem: {
            label: "修改菜单",
            action: function (node) {
                var selected = $("#tree").jstree("get_selected");
                var obj = $("#tree").jstree("get_node", selected[0]);
                editMenu(obj);
            }
        },

        deleteItem: {
            label: "删除菜单",
            action: function (node) {
                var selected = $("#tree").jstree("get_selected");
                var obj = $("#tree").jstree("get_node", selected[0]);
                deleteMenu(obj);
            }
        }
    };

    return (node.original.id === 0) ? parentMenu : sonMenu;
}

/**
 * 初始化菜单树
 */
function initTree(_this) {
    _this.jstree({
        core: {
            check_callback : true,
            themes: {
                responsive: !1
            },
            data: function(node, callback) {
                loadMenuData(node, callback);
            }
        },
        types: {
            default: {
                icon: "la la-align-left m--font-brand"
            }
        },
        state: {
            key: "contact_tree"
        },
        contextmenu: {
            items: customMenu
        },
        plugins: ["wholerow", "types", "search", "contextmenu", "contextmenubtn", "dnd"]
    }).on('move_node.jstree', function(e, data) {
        moveMenu(data);
    }).on('refresh.jstree', function () {
        var selected = _this.jstree("get_selected");
        if (selected.length === 0) {
            _this.jstree("select_node", 1);
        }
    });
}

/**
 * 绑定事件
 */
function initEvent() {
    /**
     * 点击事件
     */
    $('.tree').on("select_node.jstree", function (node, selected) {
        $("#menuName").empty();
        $(".role-select").hide();
        if (selected.node.original.id !== 0) {
            $("#menuName").text(' >> ' + selected.node.original.text);
            if (allRole) {
                selectedMenuid = selected.node.original.id;
                initRoleSelect();
            }
            $(".role-select").show();
        }
    });

    /**
     * 页面查询
     */
    $("#search").blur("propertychange", function () {
        $("#tree").jstree(true).search($.trim($(this).val()));
    });
}

jQuery(document).ready(function() {
    initTree($("#tree"));
    initEvent();
});

/**
 * 菜单滑动效果
 */
function initSwiper(){
}

/**
 * 加载菜单数据
 * @param node
 * @param callback
 */
function loadMenuData(node, callback) {
    if (node.id === "#") {
        callback.call(this, [{
            text: '遥感影像智能云检测',
            id: 0,
            state: {
                'opened': true,  //表示是否立即打开
                'selected': false, //是否选中，这边可以支持表达式，函数等
                "disabled": false //是否禁用，这边可以支持表达式，函数等
            },
            children: true   //表示是否还有子节点
        }]);
    } else {
        $.hcPostAjax({
            msgPrefix: '加载菜单数据出错：',
            url: basePath + '/menu/list',
            data: {
                fatherid: node.original.id
            },
            success: function (data) {
                var treeData = [];
                if (data !== undefined || data !== null) {
                    $(data).each(function () {
                        treeData.push(buildMenuNode(this));
                        menuData[this.id] = this;
                    });
                }
                callback.call(this, treeData);
            }
        });
    }
}

/**
 * 组装菜单节点
 * @param obj
 * @returns {{text: *, id: *, state: {opened: boolean, selected: boolean, disabled: boolean}, children: boolean}}
 */
function buildMenuNode(obj) {
    return {
        text: obj.name,
        a_attr:{"title": obj.url},
        id: obj.id,
        state: {
            'opened': false,  //表示是否立即打开
            'selected': false, //是否选中，这边可以支持表达式，函数等
            "disabled": false //是否禁用，这边可以支持表达式，函数等
        },
        children: true   //表示是否还有子节点
    };
}

/**
 * 新增菜单
 * @param node
 */
function addMenu(node) {
    layer.open({
        title: node.text + '-新建子菜单',
        type: 1,
        maxmin: true,
        area: ['60%', '80%'],
        shadeClose: true,
        content: $("#editMenuTemplate").html(),
        success: function(layero, index){
            $("#edit_menu_showLevel").selectpicker();
            /**
             * 保存菜单
             */
            form.on('submit(save_menu)', function(data){
                saveMenu(node, '新增菜单');
            });

            /**
             * 取消修改
             */
            $(".edit_cancle").on("click", function () {
                layer.closeAll();
            });
        }
    });
}

/**
 * 修改菜单
 * @param node
 */
function editMenu(node) {
    layer.open({
        title: '修改菜单',
        type: 1,
        maxmin: true,
        area: ['60%', '80%'],
        shadeClose: true,
        content: $("#editMenuTemplate").html(),
        success: function(layero, index){
            var temp_menu = menuData[node.id];
            $("#edit_menu_id").val(temp_menu.id);
            $("#edit_menu_name").val(temp_menu.name);
            $("#edit_menu_url").val(temp_menu.url);
            $("#edit_menu_description").val(temp_menu.description);
            $("#edit_menu_icon").val(temp_menu.icon);
            $("#edit_menu_fatherid").val(temp_menu.fatherid);
            $("#edit_menu_sort").val(temp_menu.sort);
            $("#edit_menu_showLevel").selectpicker();
            $("#edit_menu_showLevel").selectpicker('val', temp_menu.showLevel);
            /**
             * 保存菜单
             */
            form.on('submit(save_menu)', function(data){
                saveMenu(node, '修改菜单');
            });

            /**
             * 取消修改
             */
            $(".edit_cancle").on("click", function () {
                layer.closeAll();
            });
        }
    });
}

/**
 * 删除菜单
 * @param node
 */
function deleteMenu(node) {
    layer.confirm('确定删除<font color="red">[' + node.text + ']</font>？及其子菜单', {
        icon: 3,
        title: '提示',
        btn: ['确定','取消'] //按钮
    }, function(index){
        $.hcPostAjax({
            showLoad: true,
            msgPrefix: '删除菜单出错：',
            url: basePath + '/menu/delete',
            data: {id: node.id},
            success: function (data) {
                layer.msg('菜单删除成功！', {icon: 1,time:1500}, function () {
                    $("#tree").jstree(true).refresh();
                    $("#menuName").empty();
                    $(".role-select").hide();
                });
            }
        })
    }, function(index){
        layer.close(index);
    });
}

/**
 * 保存菜单
 */
function saveMenu(node, type) {
    var data = {
        id: $("#edit_menu_id").val(),
        name: $.trim($("#edit_menu_name").val()),
        url: $.trim($("#edit_menu_url").val()),
        description: $.trim($("#edit_menu_description").val()),
        icon: $.trim($("#edit_menu_icon").val()),
        fatherid: $.trim($("#edit_menu_fatherid").val()),
        sort: $.trim($("#edit_menu_sort").val()),
        showLevel: $("#edit_menu_showLevel").val()
    };
    if (data.id === '') {
        data['fatherid'] = node.original.id;
    }
    $.hcPostAjax({
        showLoad: true,
        msgPrefix: type + '出错：',
        url: basePath + '/menu/addOrUpdate',
        data: data,
        success: function (data) {
            layer.msg(type + '成功！', {icon: 1,time:1500}, function () {
                $("#tree").jstree(true).refresh (true,true);
                layer.closeAll();
            });
        }
    });
}

/**
 * 移动菜单位置
 * @param data
 */
function moveMenu(data) {
    var param = getMoveNodes(data);
    $.hcPostAjax({
        showLoad: true,
        msgPrefix: '移动菜单失败：',
        url: basePath + '/menu/batchUpdate',
        data: JSON.stringify(param),
        contentType: "application/json",
        success: function (result) {
            layer.msg('移动菜单成功！', {icon: 1,time:1500});
            $("#tree").jstree(true).refresh();
        }
    });
}

/**
 * 获取需要修改的节点集合
 * @param data
 * @returns {Array}
 */
function getMoveNodes(data) {
    var param = [];
    var changeParent = false;
    if (data.old_parent !== data.parent) {
        changeParent = true;
        var parent = $("#tree").jstree("get_node", data.parent);
        for (var i = data.position; i < parent.children.length; i++) {
            param.push({
                id: parent.children[i],
                sort: i,
                fatherid: parent.id
            });
        }
    }
    if (!changeParent) {
        var parent = $("#tree").jstree("get_node", data.parent),
            begin = data.position,
            end = data.old_position;
        if (begin > end) {
            begin = data.old_position;
            end = data.position;
        }
        for (;begin <= end; begin++) {
            param.push({
                id: parent.children[begin],
                sort: begin,
            });
        }
    }
    return param;
}

/**
 * 初始化角色选择
 */
function initRoleSelect() {
    $("#role-selected-option").empty();
    $.hcPostAjax({
        msgPrefix: '获取角色信息出错：',
        url: basePath + "/role/getByMenu",
        data: {menuid: selectedMenuid},
        success: function (data) {
            var flag = (data !== null && data.length > 0);
            for (var i = 0; i < allRole.length; i++) {
                allRole[i].selected = "";
                if (flag) {
                    for (var j = 0; j < data.length; j++) {
                        if (allRole[i].id === data[j].id) {
                            allRole[i].selected = "selected";
                            break;
                        }
                    }
                }
            }
            laytpl($("#roleSelectOption").html()).render({list: allRole}, function (html) {
                $("#role-selected-option").append(html);
            });
            initMulitSelect();
        }
    });
}

/**
 * 初始化设备选择div
 * @param index
 */
function initMulitSelect() {
    $('#role-selected-option').multiSelects({
        selectableHeader: "<input id='searchselectable' type='text' class='search-input form-control mulitSelectInputHeader' autocomplete='off' placeholder='请输入角色名称'>" +
        "<div class='mulitSelectDivHeader'>可选角色</div>",
        selectionHeader: "<input id='searchselection' type='text' class='search-input form-control mulitSelectInputHeader' autocomplete='off' placeholder='请输入角色名称'>" +
        "<div class='mulitSelectDivHeader'>已选角色</div>",
        afterInit: function(ms){
            var that = this,
                $selectableSearch = $('input#searchselectable'),
                $selectionSearch = $('input#searchselection'),
                selectableSearchString = '#'+that.$container.attr('id')+' .ms-elem-selectable:not(.ms-selected)',
                selectionSearchString = '#'+that.$container.attr('id')+' .ms-elem-selection.ms-selected';

            that.qs1 = $selectableSearch.quicksearch(selectableSearchString)
                .on('keydown', function(e){
                    if (e.which === 40){
                        that.$selectableUl.focus();
                        return false;
                    }
                });

            that.qs2 = $selectionSearch.quicksearch(selectionSearchString)
                .on('keydown', function(e){
                    if (e.which == 40){
                        that.$selectionUl.focus();
                        return false;
                    }
                });

            var hheight = window.innerHeight - 230;
            $("#ms-node-selected-option").css("width", "100%");
            $(".ms-list").css({"height": hheight  + "px", "border-top":"0px"});
        },
        disabledClass: "disabled",
        afterSelect: function(values){
            addRoleMenu(values[0]);
            this.qs1.cache();
            this.qs2.cache();
        },
        afterDeselect: function(values){
            removeRoleMenu(values[0]);
            this.qs1.cache();
            this.qs2.cache();
        }
    });
}

/**
 * 保存菜单角色
 * @param roleid
 */
function addRoleMenu(roleid) {
    $.hcPostAjax({
        msgPrefix: '保存菜单角色数据失败：',
        url: basePath + '/role/menu/save',
        data: {menuid: selectedMenuid, roleid: roleid},
        success: function () {
            layer.msg('保存成功！', {icon: 1,time:1500});
        }
    })
}

/**
 * 删除菜单角色
 * @param roleid
 */
function removeRoleMenu(roleid) {
    $.hcPostAjax({
        msgPrefix: '删除菜单角色数据失败：',
        url: basePath + '/role/menu/delete',
        data: {menuid: selectedMenuid, roleid: roleid},
        success: function () {
            layer.msg('删除成功！', {icon: 1,time:1500});
        }
    })
}